package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.dict.DictQueryVO;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.system.core.dao.model.SysApplication;
import com.bifang.module.system.core.dao.service.SysApplicationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.CardTypeEnum;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.vo.eduSyncJhApply.EduSyncJhApplyVO;
import com.jwsoft.manager.common.vo.eduSyncJhApprove.EduSyncJhApproveVO;
import com.jwsoft.manager.common.vo.eduSyncJhDelete.*;
import com.jwsoft.manager.common.vo.eduSyncJhEnroll.EduSyncJhEnrollVO;
import com.jwsoft.manager.core.dao.model.EduSyncJhApply;
import com.jwsoft.manager.core.dao.model.EduSyncJhApprove;
import com.jwsoft.manager.core.dao.model.EduSyncJhEnroll;
import com.jwsoft.manager.core.dao.service.EduSyncJhApplyService;
import com.jwsoft.manager.core.dao.service.EduSyncJhApproveService;
import com.jwsoft.manager.core.dao.service.EduSyncJhEnrollService;
import com.jwsoft.manager.core.integration.EduSyncJhApplyIntegration;
import com.jwsoft.manager.core.integration.EduSyncJhApproveIntegration;
import com.jwsoft.manager.core.integration.EduSyncJhEnrollIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.core.integration.EduSyncJhDeleteIntegration;
import com.jwsoft.manager.core.dao.service.EduSyncJhDeleteService;
import com.jwsoft.manager.core.dao.model.EduSyncJhDelete;

import javax.servlet.http.HttpServletRequest;

/**
 * 金华市报名删除同步情况表业务实现类
 *
 * @author zhiyuan
 * @since 2024-04-08
 */
@ApiService(funcCode = "syncJhDelete", title = "金华市报名删除同步情况表")
public class EduSyncJhDeleteIntegrationImpl implements EduSyncJhDeleteIntegration {

    @Autowired
    public EduSyncJhDeleteService eduSyncJhDeleteService;

    @Autowired
    private EduSyncJhApproveIntegration approveIntegration;

    @Autowired
    private EduSyncJhApplyIntegration applyIntegration;

    @Autowired
    private SysApplicationService applicationService;

    @Autowired
    private DictIntegration dictIntegration;

    @Autowired
    private EduSyncJhEnrollIntegration enrollIntegration;

    @Autowired
    private EduHelper eduHelper;

    @Override
    @Transactional
    @OpApi(funcCode = "syncJhDelete0001", title = "根据年份和类型删除同步学生信息",
            funcType = FuncTypeEnum.delete,savelog = true)
    public void syncJhDeleteByType(EduSyncJhDeleteQueryVO vo, HttpServletRequest request) {
        String appId = request.getHeader("appId");
        if (StringUtils.isBlank(appId)){
            throw new AppException("应用id不能为空！");
        }
        checkDelete(vo);
        //校验行政区划和当前配置的应用id 是否一样
        SysApplication sysApplication = applicationService.getById(appId);
        //根据，来分割remarks
        String remarks = sysApplication.getRemarks();
        if (StringUtils.isEmpty(remarks)){
            throw new AppException("应用id未配置行政区划，请联系管理员进行配置！");
        }
        List areaList = Arrays.asList(remarks.split(","));
        if (!areaList.contains(vo.getApplyCountyCode())){
            throw new AppException("传入的区县编码和申请的应用区县编码不一致，应用区县编码 ["+remarks+"]请根据提供的接口文档规范上传！");
        }
        DictQueryVO areaDictQueryVO = new DictQueryVO();
        areaDictQueryVO.setDictField("AREA");
        areaDictQueryVO.setDictKey(vo.getApplyCountyCode());
        String areaName = dictIntegration.getValue(areaDictQueryVO);
        if (StringUtils.isBlank(areaName)){
            throw new AppException("传入的区县编码不正确，请根据提供的接口文档规范上传！");
        }
        vo.setApplyCountyName(areaName);
        //根据类型来进行决定需要删除那张表的数据
        if(vo.getDeleteType().equals("1")){
            //报名表
            applyIntegration.syncDelete(vo);
        }else if(vo.getDeleteType().equals("2")){
            //审核表
            approveIntegration.syncDelete(vo);
        }else if(vo.getDeleteType().equals("3")){
            //录取表
            enrollIntegration.syncDelete(vo);
        }else{
            throw new AppException("要删除的类型不正确!");
        }
    }


    @Override
    @Transactional
    @OpApi(funcCode = "syncJhDelete0002", title = "金华市报名学生信息删除同步-内部接口",
            funcType = FuncTypeEnum.delete)
    public void syncJhDeleteByType2(EduSyncJhDeleteQueryVO vo) {
        checkDelete(vo);
        //根据类型来进行决定需要删除那张表的数据
        if(vo.getDeleteType().equals("1")){
            //报名表
            applyIntegration.syncDelete(vo);
        }else if(vo.getDeleteType().equals("2")){
            //审核表
            approveIntegration.syncDelete(vo);
        }else if(vo.getDeleteType().equals("3")){
            //录取表
            enrollIntegration.syncDelete(vo);
        }else{
            throw new AppException("要删除的类型不正确!");
        }
    }

    @Override
    @OpApi(funcCode = "syncJhQuery0001", title = "金华市根据类型查询学生信息是否存在-向外暴露接口",
            funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public EduSyncExistInfo querySyncInfo(EduSyncJhDeleteQueryVO vo) {
        checkQuery(vo);
        return eduSyncJhDeleteService.querySyncInfo(vo);
    }

    @Override
    @OpApi(funcCode = "syncJh0009", title = "金华市同步学生信息保存-向外暴露接口",
            funcType = FuncTypeEnum.insert)
    public void saveSyncInfo(EduSyncJhDeleteQueryVO vo) {
        saveCheck(vo);
        //根据类型，来调用各个方法保存接口
        if(vo.getSaveType().equals("1")){
            EduSyncJhApplyVO syncApplyVO =  Convert.convert(EduSyncJhApplyVO.class, vo);
            //报名表
            applyIntegration.add(syncApplyVO);
        }else if(vo.getSaveType().equals("2")){
            EduSyncJhApproveVO syncJhApproveVO = Convert.convert(EduSyncJhApproveVO.class, vo);
            //审核表
            approveIntegration.add(syncJhApproveVO);
        }else if(vo.getSaveType().equals("3")){
            EduSyncJhEnrollVO syncJhEnrollVO =  Convert.convert(EduSyncJhEnrollVO.class, vo);
            //录取表
            enrollIntegration.add(syncJhEnrollVO);
        }else{
            throw new AppException("要保存的类型不正确!");
        }

    }

    private void saveCheck(EduSyncJhDeleteQueryVO vo) {
        if (vo.getSaveType().equalsIgnoreCase("1")){
            if (StringUtils.isBlank(vo.getApplyDate())) {
                throw new AppException("报名时间不能为空！");
            }else{
                //将时间格式转换为时间搓
                if (isValidDate(vo.getApplyDate())) {
                    //如果是时间，转换为时间戳
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = null;
                    try {
                        date = dateFormat.parse(vo.getApplyDate());
                        long timestamp = date.getTime();
                        vo.setApplyTime(timestamp);
                    } catch (ParseException e) {
                        throw new AppException("报名时间格式不正确！ 正确格式如:2024-01-01 12:10:50    ");
                    }
                }else{
                    throw new AppException("报名时间格式不正确！ 正确格式如:2024-01-01 12:10:50    ");
                }
            }
        }

        Integer year = eduHelper.thisYear();
        vo.setYear(year);
        if (StringUtils.isBlank(vo.getSaveType())){
            throw new AppException("要保存的类型不能为空!");
        }
        if (!vo.getSaveType().equalsIgnoreCase("1")
                && !vo.getSaveType().equalsIgnoreCase("2")
                && !vo.getSaveType().equalsIgnoreCase("3")){
            throw new AppException("要保存的类型不正确! 只能为1/2/3  1报名表 2 审核表 3 录取表");
        }
    }

    private void checkQuery(EduSyncJhDeleteQueryVO vo) {
        if(vo.getYear() == null){
            Integer year = eduHelper.thisYear();
            vo.setYear(year);
        }

        if (StringUtils.isBlank(vo.getIdcard())) {
            throw new AppException("证件号码不能为空！");
        }
        if (StringUtils.isEmpty(vo.getName())){
            throw new AppException("姓名不能为空！");
        }
        if (vo.getAppId()!=null){
            SysApplication sysApplication = applicationService.getById(vo.getAppId());
            //根据，来分割remarks
            String remarks = sysApplication.getRemarks();
            if (StringUtils.isEmpty(remarks)){
                throw new AppException("应用id未配置行政区划，请联系管理员进行配置！");
            }
            List<String> areaList = Arrays.asList(remarks.split(","));
            if (StringUtils.isNotBlank(vo.getApplyCountyCode())&&!areaList.contains(vo.getApplyCountyCode())){
                throw new AppException("传入的区县编码和申请的应用区县编码不一致，应用区县编码 ["+remarks+"]请根据提供的接口文档规范上传！");
            }
            if (StringUtils.isBlank(vo.getApplyCountyCode())){
                if (areaList.size()>1){
                    throw new AppException("请传入当前学生的区县编码(applyCountyCode)！");
                }else{
                    vo.setApplyCountyCode(areaList.get(0));
                }
            }
        }

    }

    private void checkDelete(EduSyncJhDeleteQueryVO vo) {
        if (vo.getYear() == null){
            vo.setYear(eduHelper.thisYear());
        }
        if (StringUtils.isBlank(vo.getApplyCountyCode())) {
            throw new AppException("报名所在区县码不能为空！");
        }
        if (StringUtils.isBlank(vo.getDeleteType())){
            throw new AppException("要删除的类型不能为空!");
        }
        if (StringUtils.isBlank(vo.getIdcard())) {
            throw new AppException("证件号码不能为空！");
        }
        if (!vo.getDeleteType().equalsIgnoreCase("1")
                && !vo.getDeleteType().equalsIgnoreCase("2")
                && !vo.getDeleteType().equalsIgnoreCase("3")){
            throw new AppException("要删除的类型不正确! 只能为1/2/3  1报名表 2 审核表 3 录取表");
        }
        //校验区县码是否为数字
        if (!StringUtils.isNumeric(vo.getApplyCountyCode())) {
            throw new AppException("报名所在区县码只能为数字");
        }
    }


    private boolean isValidDate(String applyDate) {
        //判断时间是否为yyyy-MM-dd HH:mm:ss 格式
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            LocalDateTime.parse(applyDate, dtf);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }
}
